<!DOCTYPE html>
<html>
<head>
    <title>WebSoket Demo</title>
    <script type="text/javascript">
        //验证浏览器是否支持WebSocket协议
        if (!window.WebSocket) {
            alert("WebSocket not supported by this browser!");
        }
        let ws;

        const log = function (s) {
            if (document.readyState !== "complete") {
                log.buffer.push(s);
            } else {
                document.getElementById("contentId").innerHTML += (s + "\n");
            }
        };

        function display() {
            ws = new WebSocket("ws://localhost:8888/websocket");
            ws.onmessage = function (event) {
                //监听消息
                log(event.data);
            };
            ws.onclose = function (event) {
                // 关闭WebSocket
                console.log("ws close: " + event);
            };
            ws.onopen = function (event) {
                // 打开WebSocket
                console.log("ws open:" + event);
                // 发送一个初始化消息
                ws.send("Hello, Server!");
            };
            ws.onerror = function (event) {
                // WebSocket异常
                console.log("ws error:" + event);
            };
        }


        function sendMsg() {
            // 发送消息
            const msg = document.getElementById("messageId");
            ws.send(msg.value);
        }
    </script>
</head>
<body onload="display();">
    <div id="valueLabel"></div>
    <textarea rows="20" cols="30" id="contentId"></textarea>
    <br/>
    <input name="message" id="messageId"/>
    <button id="sendButton" onClick="sendMsg()">Send</button>
</body>
</html>